import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Card, Modal, Form, Input, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TablePaginationConfig } from 'antd/es/table';
import { SensitiveWordItem } from 'admin/schema/Cas';
import {
  getSensitiveWords,
  addSensitiveWord,
  updateSensitiveWord,
  deleteSensitiveWord,
  checkSensitiveWord,
} from 'admin/servers/modules/Cas';
import { debounce } from 'lodash';

interface SensitiveWordFormValues {
  word: string;
}

interface CheckFormValues {
  content: string;
}

const SensitiveWord: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [words, setWords] = useState<SensitiveWordItem[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('新增敏感词');
  const [form] = Form.useForm<SensitiveWordFormValues>();
  const [editingWord, setEditingWord] = useState<SensitiveWordItem | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [checkModalVisible, setCheckModalVisible] = useState(false);
  const [checkForm] = Form.useForm<CheckFormValues>();
  const [checkResult, setCheckResult] = useState<{
    result: boolean;
    invalidWords: string[];
  } | null>(null);

  const [searchForm] = Form.useForm();

  // 获取敏感词列表
  const fetchWords = async (page: number, pageSize = 10, word = '') => {
    setLoading(true);
    try {
      const response = await getSensitiveWords(page - 1, pageSize, { word: word || undefined });
      if (response.status === 200) {
        const { content, totalElements, number } = response.data;
        setWords(content);
        setPagination(prev => ({
          ...prev,
          current: number + 1,
          pageSize,
          total: totalElements,
        }));
      }
    } catch (error) {
      console.error('获取敏感词列表出错:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchWords(1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchWords(
      newPagination.current || 1,
      newPagination.pageSize || 10,
      searchForm.getFieldValue('word')
    );
  };

  const handleAdd = () => {
    setModalTitle('新增敏感词');
    setEditingWord(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: SensitiveWordItem) => {
    setModalTitle('编辑敏感词');
    setEditingWord(record);
    form.setFieldsValue({
      word: record.word,
    });
    setModalVisible(true);
  };

  const handleDelete = (record: SensitiveWordItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除敏感词"${record.word}"吗？`,
      onOk: async () => {
        try {
          const response = await deleteSensitiveWord(record.id);
          if (response.status === 200) {
            message.success('删除成功');
            fetchWords(pagination.current, pagination.pageSize, searchForm.getFieldValue('word'));
          }
        } catch (error) {
          console.error('删除敏感词出错:', error);
        }
      },
    });
  };

  const handleModalOk = debounce(async () => {
    try {
      const values = await form.validateFields();
      if (editingWord) {
        // 更新敏感词
        const response = await updateSensitiveWord({
          id: editingWord.id,
          word: values.word,
        });

        if (response.status === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchWords(pagination.current, pagination.pageSize, searchForm.getFieldValue('word'));
        }
      } else {
        // 新增敏感词
        const response = await addSensitiveWord({
          word: values.word,
        });

        if (response.status === 200) {
          message.success('添加成功');
          setModalVisible(false);
          fetchWords(pagination.current, pagination.pageSize, searchForm.getFieldValue('word'));
        }
      }
    } catch (error) {
      console.error('表单验证或提交出错:', error);
    }
  }, 500);

  const handleCheck = () => {
    checkForm.resetFields();
    setCheckResult(null);
    setCheckModalVisible(true);
  };

  const handleCheckOk = debounce(async () => {
    try {
      const values = await checkForm.validateFields();
      const response = await checkSensitiveWord({
        content: values.content,
      });
      if (response.status === 200) {
        setCheckResult(response.data);
      }
    } catch (error) {
      console.error('敏感词检查出错:', error);
    }
  }, 500);

  const handleReset = debounce(() => {
    searchForm.resetFields();
    fetchWords(1, 10, '');
  }, 500);

  const handleFinish = debounce((values: any) => {
    fetchWords(1, 10, values.word);
  }, 500);

  const columns: ColumnsType<SensitiveWordItem> = [
    {
      title: '敏感词',
      dataIndex: 'word',
      key: 'word',
      width: '40%',
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: '40%',
      render: time => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: '20%',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" style={{ paddingInline: 0 }} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button
            type="link"
            style={{ paddingInline: 0 }}
            danger
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title="敏感词管理"
        bordered={false}
        extra={
          <Space>
            <Button type="primary" onClick={handleCheck}>
              敏感词检查
            </Button>
            <Button type="primary" onClick={handleAdd}>
              新增敏感词
            </Button>
          </Space>
        }
      >
        <Form
          layout="inline"
          form={searchForm}
          onFinish={handleFinish}
          style={{ marginBottom: '20px' }}
        >
          <Form.Item label="敏感词" name="word">
            <Input placeholder="请输入敏感词" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={words}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showTotal: (total: number) => `共 ${total} 条`,
            showSizeChanger: true,
          }}
          onChange={handleTableChange}
        />
      </Card>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        maskClosable={false}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="word"
            label="敏感词"
            rules={[{ required: true, message: '请输入敏感词' }]}
          >
            <Input placeholder="请输入敏感词" maxLength={50} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="敏感词检查"
        visible={checkModalVisible}
        onOk={handleCheckOk}
        onCancel={() => setCheckModalVisible(false)}
        destroyOnClose
        width={600}
        maskClosable={false}
      >
        <Form form={checkForm} layout="vertical">
          <Form.Item
            name="content"
            label="待检查内容"
            rules={[{ required: true, message: '请输入待检查内容' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入待检查内容" maxLength={1000} showCount />
          </Form.Item>
        </Form>

        {checkResult && (
          <div style={{ marginTop: 16 }}>
            <div>检查结果：{checkResult.result ? '不包含敏感词' : '包含敏感词'}</div>
            {!checkResult.result && (
              <div>
                包含的敏感词：
                {checkResult.invalidWords?.map((word, index) => (
                  <span key={word} style={{ color: 'red' }}>
                    {word}
                    {index < checkResult.invalidWords.length - 1 ? '、' : ''}
                  </span>
                ))}
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default SensitiveWord;
